package com.example.androidthreadtest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView text;
    private static final int  UPDATE_TEXT = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.text);
        Button changeText = (Button) findViewById(R.id.change_text);
        changeText.setOnClickListener(this);
    }
    // 在主线程中新建一个Handler对象，并重写handleMessage方法
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TEXT:
                    // 在主线程中可以进行更新UI操作了
                    text.setText("我更新啦！");
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.change_text:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 不能在子线程更新UI，会导致程序崩溃
                        // text.setText("Nice to meet you");
                    //    使用异步消息处理机制
                        //新建Message对象
                        Message msg = new Message();
                        msg.what = UPDATE_TEXT;
                        // 通过 handler.sendMessage将消息发送出去
                        handler.sendMessage(msg);
                    }
                }).start();
                break;
            default:
                break;
        }
    }

}